package bootstrap

import (
	"fmt"
	"grpc.getaway.adminspro.padmins.com/internal/api/module/admin/container"
	"grpc.getaway.adminspro.padmins.com/pkg/config/businessError"
)

func GetRouter(method string) (func(c *container.Context) (interface{}, error), error) {
	router, ok := routers[method]
	var e error
	if ok == false {
		e = fmt.Errorf("[%s] method 不存在", method)
	}
	return router, e
}

func run(c *container.Context) {
	c.SetHandler(func(context *container.Context) {
		c.Write(func() string {
			m := c.ResponseMessage
			Request := c.Request

			method := Request.Params("method", "").(string)

			if method == "" {
				return m.JSON(businessError.MethodEmpty.Code, businessError.MethodEmpty.Msg, nil)

			}

			router, e := GetRouter(method)

			if e != nil {
				return m.JSON(businessError.NotFound.Code, e.Error(), nil)

			}

			data, e := router(c)

			if e != nil {
				err := businessError.RpcErrorToErrorInfo(e)
				c.Logger.Error(err.Error(), data)
				if err != nil {
					return m.JSON(err.Code, err.Msg, data)
				}

				if se, ok := e.(interface {
					GetCode() int
					GetMsg() string
				}); ok {
					return m.JSON(se.GetCode(), se.GetMsg(), data)
				}

				return m.JSON(businessError.SystemError.Code, e.Error(), data)
			}
			c.Logger.Info("请求成功", data)
			return m.JSON(0, "success", data)
		}())
	})

	// 设置handle
	c.Handle()
}
